﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Data;
using VAdvantage.Framework;
using System.Text;

namespace VAdvantage.Common
{
    /// <summary>
    /// Fills error log
    /// </summary>
    public class ErrorLog
    {
        // declare variables
        static DataTable dtLog = null;
        static int totErrors = 0;

        /// <summary>
        /// Add columns in Error DataTable if datatable is empty
        /// </summary>
        /// <author>Veena Pandey</author>
        private static void AddColumns()
        {
            if (dtLog == null)
            {
                // add columns
                dtLog = new DataTable("ErrorLog");
                DataColumn dc;
                dc = new DataColumn("Time");
                dtLog.Columns.Add(dc);
                dc = new DataColumn("Level");
                dtLog.Columns.Add(dc);
                dc = new DataColumn("Class");
                dtLog.Columns.Add(dc);
                dc = new DataColumn("Message");
                dtLog.Columns.Add(dc);
                //dc = new DataColumn("Parameter");
                //dtLog.Columns.Add(dc);
                dc = new DataColumn("Trace");
                dtLog.Columns.Add(dc);
            }
        }

        /// <summary>
        /// Fills error/info/warning in log
        /// </summary>
        /// <param name="classMethod"> of pattern "ClassName.MethodName"</param>
        /// <param name="sqlQuery">query where error occured or any message</param>
        /// <param name="errorMsg">full error message</param>
        /// <param name="messageType">error type from Message.MessageType enum</param>
        /// <author>Veena Pandey</author>
        public static void FillErrorLog(string classMethod, string sqlQuery, string errorMsg, Message.MessageType messageType)
        {
            AddColumns();

            string level = "";
            // check level according to messageType given
            switch (messageType)
            {
                case Message.MessageType.ERROR:
                    level = "SEVERE";
                    break;
                case Message.MessageType.INFORMATION:
                    level = "INFO";
                    break;
                case Message.MessageType.WARNING:
                    level = "WARNING";
                    break;
                default:
                    level = "INFO";
                    break;
            }
            // add a new row and store all values given in it.
            DataRow dr = dtLog.NewRow();
            dr[0] = DateTime.Now.ToString();
            dr[1] = level;
            dr[2] = classMethod;
            dr[3] = sqlQuery;
            dr[4] = errorMsg;
            // add above new datator in error datatable
            dtLog.Rows.Add(dr);
        }

        /// <summary>
        /// Get the log of errors
        /// </summary>
        /// <param name="isErrorOnly">true if only errors else includes info,warning also</param>
        /// <returns>DataView of log</returns>
        /// <author>Veena Pandey</author>
        public static DataView GetErrorLog(bool isErrorOnly)
        {
            // add columns if datatable is null
            AddColumns();

            // if user wants only error log
            if (isErrorOnly)
            {
                //return dtLog.Select("Level='SEVERE'");
                //totErrors = 0;
                //DataTable dtRaw = dvMainLog.ToTable();

                // copy the error datatable to another datatable

                DataTable dtRaw = (DataTable)dtLog.Copy(false);
                DataView dv = new DataView();

                //dv = dtRaw.DefaultView;
                dv.Table = dtRaw;
                // add a filter in dtRaw

                //dv.RowFilter = "Level='SEVERE'";
                //dv.RowFilter = "Level='SEVERE'";sss

                if (dv.Table != null)
                {
                    // store total number of rows
                    //totErrors = dv.Count;
                    totErrors = dv.Rows.Count;
                }
                // return dataview containing errors only
                return dv;
            }
            else
            {
                // if user wants whole log

                // DataView dvMLog = dtLog.DefaultView;
                DataView dvMLog = new DataView();
                dvMLog.Table = dtLog;

                // store total number of rows in log
                totErrors = dvMLog.Table.Rows.Count;
                // return dataview containg all log
                return dvMLog;
            }
        }

        /// <summary>
        /// Clears the log
        /// </summary>
        /// <param name="isErrorOnly">true if only errors else includes info,warning also</param>
        /// <author>Veena Pandey</author>
        public static void ResetErrorLog(bool isErrorOnly)
        {
            // if user wants to clear only error log
            if (isErrorOnly)
            {
                //dvMainLog = dtLog.DefaultView;
                //dvMainLog.RowFilter = "Level<>'SEVERE'";

                // get total rows
                int totCnt = dtLog.Rows.Count;
                for (int iRow = 0; iRow < totCnt; iRow++)
                {
                    try
                    {
                        // removes error row from log datatable
                        DataRow dRow = dtLog.Rows[iRow];
                        if (dRow["Level"].ToString() == "SEVERE")
                        {
                            dtLog.Rows.Remove(dRow);
                        }
                    }
                    catch (Exception ex)
                    { }
                }
            }
            else
            {
                // if user wants to clear whole log, then clear whole log
                dtLog.Clear();
            }
        }

        /// <summary>
        /// Save the preference information to a file
        /// </summary>
        /// <param name="filePath">path where to save the file</param>
        /// <param name="extraContent">some extra content to be added in file</param>
        /// <param name="isErrorOnly">true if only errors else includes info,warning also</param>
        /// <author>Veena Pandey</author>
  //      public static void SaveLogToFile(string filePath, bool isErrorOnly, string extraContent)
        public static void SaveLogToFile(SaveFileDialog filePath, bool isErrorOnly, string extraContent)
        {
            // initialize a stream writer with given path
            System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath.OpenFile());
            // write the extra content into stream
            writer.Write(extraContent + "\r\n");
            // get log content and writes into stream
            writer.Write(ErrorFileContent(isErrorOnly));
            //close the stream
            writer.Close();
        }

        /// <summary>
        /// Get log file content
        /// </summary>
        /// <param name="isErrorOnly">true if only errors else includes info,warning also</param>
        /// <returns>string</returns>
        /// <author>Veena Pandey</author>
        public static string ErrorFileContent(bool isErrorOnly)
        {
            // get log's dataview
            DataView dvLogFile = GetErrorLog(isErrorOnly);
            // convert dataview to datatable
            //DataTable dtLogFile = dvLogFile.ToTable();
            DataTable dtLogFile = dvLogFile.Table;

            StringBuilder content = new StringBuilder();
            // if datatable contains any row
            if (dtLogFile.Rows.Count > 0)
            {
                // for every row of datatable
                for (int iRow = 0; iRow < dtLogFile.Rows.Count; iRow++)
                {
                    // add a row separater
                    content.Append("-------------------------------\r\n");
                    // for every column of datarow
                    for (int iCol = 0; iCol < dtLogFile.Columns.Count; iCol++)
                    {
                        //get datarow
                        DataRow dRow = dtLogFile.Rows[iRow];
                        // if last column, add the column content to string builder
                        if (iCol == dtLogFile.Columns.Count - 1)
                        {
                            content.Append(dRow[iCol].ToString());
                        }
                        else
                        {
                            // add the column content to string builder along with a column separater(:)
                            content.Append(dRow[iCol].ToString() + ": ");
                        }
                    }
                }
            }
            //return content
            return content.ToString();
        }

        /// <summary>
        /// Get total number of records in log file
        /// </summary>
        /// <returns>integer-total records</returns>
        /// <author>Veena Pandey</author>
        public static int GetTotRecords()
        {
            // return total records in log datatable
            return totErrors;
        }
    }
}
